package com.gitee.hermer.engine.jars.core.execute.manage.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gitee.hermer.boot.jee.commons.verify.Assert;
import com.gitee.hermer.engine.jars.core.context.IEngineAppContext;
import com.gitee.hermer.engine.jars.core.context.domain.EngineAppContext;
import com.gitee.hermer.engine.jars.core.execute.EngineExecuteCallable;
import com.gitee.hermer.engine.jars.core.execute.EngineExecuteRunnable;
import com.gitee.hermer.engine.jars.core.execute.EngineExecuteThread.LifeCycle;
import com.gitee.hermer.engine.jars.core.execute.domain.EngineResponseBody;
import com.gitee.hermer.engine.jars.core.execute.domain.ExecuteParamsInfo;
import com.gitee.hermer.engine.jars.core.execute.manage.IEngineExecutePoolManager;
import com.gitee.hermer.engine.jars.starter.thread.pool.IThreadPoolManage;
import com.gitee.hermer.engine.jars.starter.thread.pool.callback.CallableResult;

@Component
public class EngineExecuteManageImpl implements IEngineExecutePoolManager{
	
	@Autowired
	private IThreadPoolManage poolManage;
	
	@Autowired
	private IEngineAppContext appContextService;

	@Override
	public void executeAsyn(EngineExecuteRunnable runnable) throws Throwable {
		Assert.notNull(runnable);
		poolManage.executeAsyn(runnable);
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		
	}

	@Override
	public void destroy() throws Exception {
		poolManage.destroy();
	}
	@Override
	public <V> void executeAsyn(EngineExecuteCallable<V> runnable,CallableResult<V> callableResult) throws Throwable {
		Assert.notNull(runnable);
		poolManage.executeAsyn(runnable,callableResult);
	}
	@Override
	public <V> V execute(EngineExecuteCallable<V> runnable) throws Throwable {
		return poolManage.execute(runnable);
	}
	@Override
	public <V> V execute(String projectName, String version, String workMethod, String workVersion, Object[] finArgs)
			throws Throwable {
		final EngineAppContext appContext = this.appContextService.getEnableAppModelContext(projectName, workVersion);
		return poolManage.execute(new EngineExecuteCallable<V>(appContext.getJobContext(),appContext.getCacheKey(),
				new ExecuteParamsInfo(projectName, version, workMethod, workVersion, finArgs),LifeCycle.AT_WORK) {

					@Override
					public V onExecute() throws Throwable{
						return appContext.invokeEngineAppJob(workMethod, workVersion, finArgs);
					}
			
		});
		
		
	}

}
